package com.zhangqiang.git.auth2secrity.framework.security;

import com.zhangqiang.git.auth2secrity.framework.config.OAuth2Config;
import com.zhangqiang.git.auth2secrity.framework.security.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName: SecurityConfig
 * @Description: Security配置
 * @author: zhangqiang
 * @date: 2021/3/1
 * 
 */
@Configuration
//@Order(1) 设置WebSecurityConfigurerAdapter等级
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	CustomUserDetailsService userDetailsService;

	@Autowired
	private OAuth2Config oAuth2Config;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// 开启formLogin模
			.formLogin()
				.and()
			// 配置权限
			.authorizeRequests()
				// 无需拦截请求设置   /oauth/authorize授权请求接口
				.antMatchers(oAuth2Config.getAntPatterns()).permitAll()
				// 其他请求全部需要验证
				.anyRequest().authenticated()
				.and()
			// csrf 跨域处理
			.csrf().disable();
	}

//	@Override
//	protected void configure(AuthenticationManagerBuilder auth)
//			throws Exception {
//		auth.userDetailsService(userDetailsService) // 认证信息存储(自定义)
//				.passwordEncoder(passwordEncoder());// 加密方式
//	}

	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		AuthenticationManager manager = super.authenticationManagerBean();
		return manager;
	}
}
